package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ShoppingCartMapper;
import com.itheima.pojo.Code;
import com.itheima.pojo.Result;
import com.itheima.pojo.ShoppingCart;
import com.itheima.service.ShoppingCartService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Log4j2
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;


    /**
     * 购物车添加
     *
     * @param shoppingCart
     * @return
     */
    @Override
    @Transactional
    public Result add(ShoppingCart shoppingCart) {
    //    先查询购物中是否有该商品
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("dish_id", shoppingCart.getDishId());
        ShoppingCart one = shoppingCartMapper.selectOne(wrapper);
        //有该商品原有数量加1 没有也添加
        if (one!= null){
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.set("number", one.getNumber()+1);
            update(updateWrapper);
            return new Result(Code.OK, "添加成功", "{}");
        }

        shoppingCartMapper.insert(shoppingCart);
        return new Result(Code.OK,"添加成功","{}");

    }

    /**
     * 删除购物车
     * @param
     * @return
     */
    @Override
    public Result delete() {
     shoppingCartMapper.delete(null);
            return new Result(Code.OK, "清空购物车成功", "{}");
        }



    /**
     * 删除购物车商品
     *
     * @param
     * @param shoppingCart
     * @return
     */
    @Transactional
    @Override
    public Result deleteById(ShoppingCart shoppingCart) {
        //判断是单品还是套餐
        QueryWrapper wrapper = new QueryWrapper();
        if (shoppingCart.getDishId()!=null){
            wrapper.eq("dish_id", shoppingCart.getDishId());
        }else {
            wrapper.eq("setmeal_id", shoppingCart.getSetmealId());
        }
       shoppingCartMapper.delete(wrapper);
        //再查一次购物车列表
        List<ShoppingCart> list = shoppingCartMapper.selectList(null);
        return  new Result(Code.OK, list, "{}");
    }

    /**
     * 购物车列表
     * @return
     */
    @Override
    public Result listAll() {
        // List<ShoppingCart> list = shoppingCartService.list();
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(null);
        return new Result(Code.OK,shoppingCarts,"{}");
    }
}
